/**
 * @(#)MailSender.java, 2010-5-16. 
 * 
 */
package com.rsstuan.mail;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import com.rsstuan.data.TuanGouWebItem;
import com.rsstuan.service.ChannelService;
import com.rsstuan.storage.data.MailSubscribeData;
import com.rsstuan.storage.data.TuanGouChannelData;
import com.rsstuan.storage.data.TuanGouItemData;
import com.rsstuan.storage.impl.JDOMailSubscribeStorage;
import com.rsstuan.storage.impl.JDOTuanGouChannelStorage;
import com.rsstuan.storage.impl.JDOTuanGouItemStorage;
import com.rsstuan.utils.ItemUtils;
import com.rsstuan.utils.StringUtils;


/**
 *
 * @author guosq
 *
 */
public class MailSender {
    
    private static final Logger LOG = Logger.getLogger(MailSender.class.getName());
    
    private VelocityConfigurer velocityConfig;
    
    private Properties props;
    
    private Session session;
    
    
    public MailSender() {
         props = new Properties();
         session = Session.getDefaultInstance(props, null);
    }
    
    public void sendFeedBack(String from, String title, String content) {
        StringBuilder sb = new StringBuilder();
        String subject = "[团四方反馈]用户" + from + "发来的反馈意见"; 
        sb.append("用户: " + from + "<br/>");
        sb.append("标题: " + title + "<br/>");
        sb.append("内容: "+ content);
        
        send("no-reply@tuansifang.com", "feed-back@tuansifang.com", subject, sb.toString());
    }

    public void send(String from, String to, String subject, String content) {
        try {
            Message msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(from,  MimeUtility.encodeText(from, "gb2312", "B")));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(to, MimeUtility.encodeText(to, "gb2312", "B")));
     
            msg.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));
           
            Multipart mp = new MimeMultipart();
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(content, "text/html");
            mp.addBodyPart(htmlPart);
            msg.setContent(mp);
            Transport.send(msg);
        } catch (Exception e) {
            LOG.log(Level.WARNING, "fail to send email", e);
        }
    }
    
    
   
    public  void sendDailyMail(String city) {
        try {
           
            LOG.info("enter sendDailyMail");
            JDOMailSubscribeStorage mailStorage = new JDOMailSubscribeStorage();
            List<MailSubscribeData> subs = mailStorage.getAllSubs();
            String msgBody = constructDailyMail(city);
            for (MailSubscribeData sub : subs) {
                if (!sub.getCity().equals(city)) {
                    continue;
                }
                Message msg = new MimeMessage(session);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String subject = "团四方今日团购信息汇总 " + sdf.format(new Date(System.currentTimeMillis()));
                String fromName =  "团四方";
                String toName = sub.getEmail();
                msg.setFrom(new InternetAddress("info@tuansifang.com",  MimeUtility.encodeText(fromName, "gb2312", "B")));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress(sub.getEmail(), MimeUtility.encodeText(toName, "gb2312", "B")));
         
                msg.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));
                
                Multipart mp = new MimeMultipart();
    
                MimeBodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(msgBody, "text/html");
                mp.addBodyPart(htmlPart);
    
               
                msg.setContent(mp);
                Transport.send(msg);
            }
            LOG.info("finish sendDailyMail");

        } catch (AddressException e) {
            LOG.log(Level.WARNING, "sendDailyMail address error", e);
        } catch (MessagingException e) {
            LOG.log(Level.WARNING, "sendDailyMail fail", e);
        } catch (UnsupportedEncodingException e) {
            LOG.log(Level.WARNING, "sendDailyMail unsupported encoding", e);
        } catch (Exception e) {
            LOG.log(Level.WARNING, "sendDailyMail exception", e);
        }
    }
    
    public  void sendDailyMailTest(String city) {
        try {
           
            LOG.info("enter sendDailyMail");
            JDOMailSubscribeStorage mailStorage = new JDOMailSubscribeStorage();
            List<MailSubscribeData> subs = mailStorage.getAllSubs();
            String msgBody = constructDailyMail(city);
            MailSubscribeData sub = new MailSubscribeData();
            sub.setEmail("siqiguo@gmail.com");
            sub.setCity(city);
                Message msg = new MimeMessage(session);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String subject = "团四方今日团购信息汇总 " + sdf.format(new Date(System.currentTimeMillis()));
                String fromName =  "团四方";
                String toName = sub.getEmail();
                msg.setFrom(new InternetAddress("info@tuansifang.com",  MimeUtility.encodeText(fromName, "gb2312", "B")));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress(sub.getEmail(), MimeUtility.encodeText(toName, "gb2312", "B")));
         
                msg.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));
                
                Multipart mp = new MimeMultipart();
    
                MimeBodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(msgBody, "text/html");
                mp.addBodyPart(htmlPart);
    
               
                msg.setContent(mp);
                Transport.send(msg);
            
            LOG.info("finish sendDailyMail");

        } catch (AddressException e) {
            LOG.log(Level.WARNING, "sendDailyMail address error", e);
        } catch (MessagingException e) {
            LOG.log(Level.WARNING, "sendDailyMail fail", e);
        } catch (UnsupportedEncodingException e) {
            LOG.log(Level.WARNING, "sendDailyMail unsupported encoding", e);
        } catch (Exception e) {
            LOG.log(Level.WARNING, "sendDailyMail exception", e);
        }
    }
    
    private String constructDailyMail(String city) throws Exception {
        JDOTuanGouItemStorage itemStorage = new JDOTuanGouItemStorage();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
       
        Map<String, Object> context = new HashMap<String, Object>();
        
        Map<Long, TuanGouChannelData> channelMap = ChannelService.getInstance().getAllChannelsMap();
        TuanGouItemData[]  items = itemStorage.getActiveItemsByCity(city);
    
        List<TuanGouWebItem> webItems = new ArrayList<TuanGouWebItem>();
        for (TuanGouItemData item : items) {
            if (ItemUtils.validate(item)) {
                TuanGouWebItem witem = new TuanGouWebItem(item);
                TuanGouChannelData channel = channelMap.get(item.getChannelId());
                if (channel != null)
                    witem.setSiteName(channel.getTitle());
                webItems.add(witem);
            }
        }
        TuanGouWebItem[] witemArray = webItems.toArray(new TuanGouWebItem[0]);
        ItemUtils.sortByOrderNumDesc(witemArray);
        String template = "mail/email.vm";
        context.put("items", witemArray);
        context.put("date", sdf.format(System.currentTimeMillis()));
        context.put("city", city);
        context.put("StringUtils", StringUtils.getInstance());
        StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityConfig.getVelocityEngine(), template, context, writer);
        return writer.toString();
        
        
    }

    public void setVelocityConfig(VelocityConfigurer velocityConfig) {
        this.velocityConfig = velocityConfig;
    }

    public VelocityConfigurer getVelocityConfig() {
        return velocityConfig;
    }

}
